package com.leyou.sms.listener;

import com.aliyuncs.exceptions.ClientException;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author CHERRY
 * @date 2018-09-15-11:36
 */
@Component
public class SmsListener {

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private SmsUtils smsUtils;

    /**
     * 监听短信消息
     *
     * @param map
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "LEYOU.SMS.QUEUE", durable = "true"),
            exchange = @Exchange(value = "LEYOU.SMS.EXCHANGE", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
            key = {"sms.captcha"}
    ))
    public void listenSms(Map<String, String> map) throws ClientException {

        if (CollectionUtils.isEmpty(map)) {
            return;
        }
        //验证码
        String code = map.get("code");
        //手机号
        String phone = map.get("phone");
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(phone)) {
            return;
        }

        smsUtils.sendSms(phone, code, smsProperties.getSignName(), smsProperties.getVerifyCodeTemplate());

    }
}
